﻿using cooc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ClientServer
{

    public static class BinaryReaderHelper
    {
        public static IRCMessage ReadMessage(this BinaryReader me)
        {
            return new IRCMessage() { user = me.ReadString(), message = me.ReadString() };
        }

        public static void WriteMessage(this BinaryWriter me, IRCMessage msg)
        {
            me.Write(msg.user);
            me.Flush();
            me.Write(msg.message);
            me.Flush();
        }
    }

    class DeamonConnector
    {
        private static Queue<IRCMessage> recive_message_queue = new Queue<IRCMessage>();
        private static Queue<IRCMessage> send_message_queue = new Queue<IRCMessage>();
        TcpClient deamonclient;
        Thread recive_loop_thread;
        Thread send_loop_thread;
        NetworkStream stream;
        BinaryReader reader;
        BinaryWriter writer;
        private static DeamonConnector instance = new DeamonConnector();
        public static DeamonConnector Instance { get => instance; private set => instance = value; }

        private DeamonConnector()
        {
            deamonclient = new TcpClient();
            //Local port listen on port 666
            deamonclient.ConnectAsync(IPAddress.Parse("127.0.0.1"), 666);
            recive_loop_thread = new Thread(Recive);
            send_loop_thread = new Thread(Sender);
            stream = deamonclient.GetStream();
            reader = new BinaryReader(stream);
            writer = new BinaryWriter(stream);
        }

        internal void ReCreateInstance()
        {
            Instance = new DeamonConnector();
        }

        public static void Recive()
        {
            while (Instance.deamonclient.Connected)
            {
                recive_message_queue.Enqueue(Instance.reader.ReadMessage());

                Thread.Sleep(1);
            }
        }
        
        public void Enqueue(IRCMessage msg)
        {
            send_message_queue.Enqueue(msg);
        }

        public static void Sender()
        {
             while(true)
            {
                if(send_message_queue.Count > 0)
                {
                    Instance.writer.WriteMessage(send_message_queue.Dequeue());
                }
            }
        }
    }
}
